package com.tihi.sina.share;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

/**
 * 图片处理
 * @author tihi
 * 2015-8-24 11:19:56
 */
public class BitmapUtil {
	
	/** 图片压缩目标大小 */
	private static final int THUMB_MAX_SIZE = 32;

	public static Bitmap bmpCompressForBm(final Bitmap bmp) {
		return BitmapFactory.decodeStream(new ByteArrayInputStream(bmpCompressForByte(bmp)));
	}
	
	public static byte[] bmpCompressForByte(final Bitmap bmp) {
		return compressBmp(bmp, true);
	}
	
	public static byte[] compressBmp(final Bitmap bmp, final boolean needRecycle) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
		
		if(out.toByteArray().length > THUMB_MAX_SIZE * 1024) {
			//先压缩一次，再微调
	        float zoom = (float)Math.sqrt(THUMB_MAX_SIZE * 1024 / (float)out.toByteArray().length);
	        Matrix matrix = new Matrix();
	        matrix.setScale(zoom, zoom);
	        Bitmap tmpBm = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), bmp.getHeight(), matrix, true);
	        out.reset();
	        tmpBm.compress(Bitmap.CompressFormat.JPEG, 85, out);
	        
	        while(out.toByteArray().length > THUMB_MAX_SIZE * 1024){
	            System.out.println(out.toByteArray().length);
	            matrix.setScale(0.9f, 0.9f);
	            tmpBm = Bitmap.createBitmap(tmpBm, 0, 0, tmpBm.getWidth(), tmpBm.getHeight(), matrix, true);
	            out.reset();
	            tmpBm.compress(Bitmap.CompressFormat.PNG, 85, out);
	        } 
		}
        
        if(needRecycle) {
        	bmp.recycle();
        }
		
		byte[] result = out.toByteArray();
		try {
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
